package com.mall.b2c.template.directive;

import static com.mall.common.directive.DirectiveUtils.OUT_LIST;
import static freemarker.template.ObjectWrapper.DEFAULT_WRAPPER;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Repository;

import com.mall.b2c.bean.AdvertBean;
import com.mall.b2c.hessian.CacheService;
import com.mall.common.directive.DirectiveUtils;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 广告标签
 */
@Repository
public class AdvertDirective extends BaseDirective   {
	
	/** 输入参数，广告个数**/
	public static final String PARAM_NUM = "num";
	/**广告位置ID**/
	public static final String ADVERTPOSITION = "position";
	
	@Resource private CacheService cacheService;

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void execute(Environment env, Map params, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {	
		String position = DirectiveUtils.getString(ADVERTPOSITION, params);
		Integer num = DirectiveUtils.getInt(PARAM_NUM, params);
		List<AdvertBean> list= cacheService.getAdverts(position, num);			
		Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params);
		paramWrap.put(OUT_LIST, DEFAULT_WRAPPER.wrap(list));
		Map<String, TemplateModel> origMap = DirectiveUtils.addParamsToVariable(env, paramWrap);
		body.render(env.getOut());
		DirectiveUtils.removeParamsFromVariable(env, paramWrap, origMap);
	}	
}
